package com.java.framework.utils;

import com.google.common.collect.Lists;
import com.java.framework.utils.Criterion.Operator;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.MatchMode;

import java.util.Collection;
import java.util.Map;

public class CriteriaUtils {

	/**
	 * 组装查询条件
	 * @return Criteria
	 */
	public static <T> Criteria<T> buildCriteria(Map<String, Object> searchParams) {
		Criteria<T> criteria = new Criteria<T>() ;
		for (Map.Entry<String, Object> entry : searchParams.entrySet()) {
			// 过滤掉空值
			String key = entry.getKey();
			Object value = entry.getValue();
			if (value == null || StringUtils.isBlank(value.toString())) {
				continue;
			}

			// 拆分Operator与filedName
			String[] names = StringUtils.split(key, "_");
			if (names.length != 2) {
				throw new IllegalArgumentException(key + " is not a valid search filter name");
			}
			String fieldName = names[0];
			Operator operator = Operator.valueOf(StringUtils.upperCase(names[1]));

			// 创建Criteria
			Criterion<T> criterion = null;
			switch(operator){
			case EQ:
				criterion = Restrictions.eq(fieldName, value);
				break;
			case NE:
				criterion = Restrictions.ne(fieldName, value);
				break;
			case LIKE:
				criterion = Restrictions.like(fieldName, value.toString());
				break;
			case LLIKE:
				criterion = Restrictions.like(fieldName, value.toString(), MatchMode.START);
				break;
			case RLIKE:
				criterion = Restrictions.like(fieldName, value.toString(), MatchMode.END);
				break;
			case GT:
				criterion = Restrictions.gt(fieldName, value);
				break;
			case LT:
				criterion = Restrictions.lt(fieldName, value);
				break;
			case GE:
				criterion = Restrictions.gte(fieldName, value);
				break;
			case LE:
				criterion = Restrictions.lte(fieldName, value);
				break;
			case IN:
				Collection<String> col = Lists.newArrayList(value.toString().split(","));
				criterion = Restrictions.in(fieldName, col, true);
				break;
			case NIN:
				Collection<String> coll = Lists.newArrayList(value.toString().split(","));
				criterion = Restrictions.notIn(fieldName, coll, true);
				break;
			default:
				break;
			}
			
			criteria.add(criterion);
		}
		return criteria;
	}
}
